<script setup>
import { getCurrentInstance, nextTick, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const tableData = ref([])
const { proxy } = getCurrentInstance()
const getUserData = async () => {
  let data = await proxy.$api.getUserData(config)
  tableData.value = data.list.map((item) => ({
    ...item,
    sexLabel: item.sex === '1' ? '男' : '女',
  }))
  config.total = data.count
}
const tableLabel = reactive([
  {
    prop: 'name',
    label: '姓名',
  },
  {
    prop: 'age',
    label: '年龄',
  },
  {
    prop: 'sexLabel',
    label: '性别',
  },
  {
    prop: 'birth',
    label: '出生日期',
    width: 200,
  },
  {
    prop: 'addr',
    label: '地址',
    width: 400,
  },
])
onMounted(() => {
  getUserData()
})
// 实现搜索
const formInline = reactive({
  keyword: '',
})
const config = reactive({
  name: '',
  total: 0,
  page: 1,
})
const handleSearch = () => {
  config.name = formInline.keyword
  getUserData()
}
const hanldeChange = (page) => {
  config.page = page
  getUserData()
}
// 实现删除
const handleDelete = (val) => {
  ElMessageBox.confirm('确定删除吗?').then(async () => {
    await proxy.$api.deleteUser({ id: val.id })
    ElMessage({
      showClose: true,
      message: '删除成功',
      type: 'success',
    })
    await getUserData()
  })
}
// 新增/编辑弹窗
// 控制对话框是否显示
const dialogVisible = ref(false)
// 区分新增/编辑
const action = ref('add')
// 表单数据对象
const formUser = reactive({})
// 校验规则
const rules = reactive({
  name: [{ required: true, message: '姓名是必填项', trigger: 'blur' }],
  age: [
    { required: true, message: '年龄是必填项', trigger: 'blur' },
    { type: 'number', message: '年龄必须是数字' },
  ],
  sex: [{ required: true, message: '性别是必选项', trigger: 'change' }],
  birth: [{ required: true, message: '出生日期是必选项' }],
  addr: [{ required: true, message: '地址是必填项' }],
})
// 日期格式化yyyy-mm-dd
const timeFormat = (time) => {
  var time = new Date(time)
  var year = time.getFullYear()
  var month = time.getMonth() + 1
  var date = time.getDate()

  function add(m) {
    return m < 10 ? '0' + m : m
  }

  return year + '-' + add(month) + '-' + add(date)
}
// 点X关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
}
// 头部新增按钮
const handleAdd = () => {
  dialogVisible.value = true
  action.value = 'add'
}
// 弹窗取消按钮
const handleCancel = () => {
  dialogVisible.value = false
  // 变量重置
  Object.keys(formUser).forEach((key) => {
    formUser[key] = '' // 根据属性类型调整初始值
  })
}
// 弹窗确定按钮
const onSubmit = () => {
  // 执行userForm表单的validate进行规则校验，
  // 传入一个回调函数，回调函数会接受到一个是否校验通过的变量
  proxy.$refs['userForm'].validate(async (valid) => {
    // 校验成功
    if (valid) {
      // res接收添加用户或者编辑用户接口的返回值
      let res = null
      // 对日期进行格式化
      formUser.birth = /^\d{4}-\d{2}-\d{2}$/.test(formUser.birth)
        ? formUser.birth
        : timeFormat(formUser.birth)
      // 对当前操作进行判断，新增/编辑
      if (action.value === 'add') {
        // 新增调用新增接口
        res = await proxy.$api.addUser(formUser)
      } else if (action.value === 'edit') {
        // 编辑
        res = await proxy.$api.editUser(formUser)
      }
      // 如果接口调用成功，重置表单，关闭弹窗，重新请求数据
      if (res) {
        dialogVisible.value = false
        proxy.$refs['userForm'].resetFields()
        getUserData()
      }
      // 校验失败，提示错误信息
    } else {
      ElMessage({
        showClose: true,
        message: '请输入正确信息',
        type: 'error',
      })
    }
  })
}
// 编辑按钮
const handleEdit = (val) => {
  action.value = 'edit'
  dialogVisible.value = true
  nextTick(() => {
    Object.assign(formUser, { ...val, sex: '' + val.sex })
  })
}
</script>

<template>
  <!-- 头部 -->
  <div class="user-header">
    <el-button type="primary" @click="handleAdd">新增</el-button>
    <el-form :inline="true" :model="formInline">
      <el-form-item label="请输入">
        <el-input v-model="formInline.keyword" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜素</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 用户信息列表 -->
  <div class="table">
    <el-table :data="tableData" style="width: 100%">
      <el-table-column
        v-for="item in tableLabel"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width ? item.width : 125"
      />
      <el-table-column fixed="right" label="Operations" min-width="120">
        <template #="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)"> 编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :total="config.total"
      class="pager"
      layout="prev, pager, next,jumper, ->, total"
      @current-change="hanldeChange"
    />
  </div>
  <!-- 新增/编辑弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :before-close="handleClose"
    :title="action === 'add' ? '新增用户' : '编辑用户'"
    width="35%"
  >
    <!--需要注意的是设置了:inline="true"，会对el-select的样式造成影响，我们通过给他设置一个class=select-clearn
 在css进行处理 ref="userForm：给表单设置引用名，便于通过 ref 调用表单方法（如验证、重置等-->
    <el-form ref="userForm" :inline="true" :model="formUser" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formUser.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="formUser.age" placeholder="请输入年龄" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item class="select-clearn" label="性别" prop="sex">
            <el-select v-model="formUser.sex" placeholder="请选择">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker
              v-model="formUser.birth"
              placeholder="请输入"
              style="width: 100%"
              type="date"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="formUser.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button type="primary" @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<style lang="less" scoped>
.user-header {
  display: flex;
  justify-content: space-between;
}

.table {
  position: relative;
  height: 520px;

  .pager {
    position: absolute;
    right: 10px;
    bottom: 30px;
  }

  .el-table {
    width: 100%;
    height: 500px;
  }
}

.select-clearn {
  display: flex;
}
</style>
